from duckduckgo_search import ddg
from langchain.agents import initialize_agent, AgentType
from langchain.llms import OpenAI
from langchain.tools import BaseTool

class DuckDuckGoTool(BaseTool):
    name = "DuckDuckGo"
    description = "Search the web using DuckDuckGo."

    def _run(self, query):
        results = ddg(query, max_results=3)
        return "\n".join([result["title"] + ": " + result["href"] for result in results])

# 初始化工具
ddg_tool = DuckDuckGoTool()

# 初始化 LLM
llm = OpenAI(temperature=0)

# 初始化 Agent
agent = initialize_agent(
    tools=[ddg_tool],
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,
)

# 测试一下
query = "Langchain 如何使用 DuckDuckGo"
response = agent(query)
print(response)
